from odoo import fields, models, api


class SProductLock(models.Model):
    _inherit = 's.product.lock'

    purchase_requisition_id = fields.Many2one('purchase.requisition', string='purchase requisition', readonly=True, copy=False)
    purchase_requisition_line_id = fields.Many2one('purchase.requisition.line', string='purchase requisition line', readonly=True, copy=False)
    purchase_requisition_date = fields.Datetime('purchase requisition date')
    purchase_qty = fields.Float('purchase qty', digits='Product Unit of Measure', compute='_compute_qty')
    incoming_qty = fields.Float('incoming qty', digits='Product Unit of Measure', compute='_compute_qty')

    date_planned = fields.Date(string='Expected Arrival', related="purchase_id.s_date_planned")

    @api.depends('purchase_requisition_id.state', 'purchase_requisition_id.pr_line_ids.qty_received')
    def _compute_qty(self):
        for rec in self:
            if rec.purchase_requisition_id.state not in ('approved', 'section_purchasing', 'purchasing', 'closed', 'done'):
                rec.purchase_qty = 0
                rec.incoming_qty = 0
                continue

            line = rec.purchase_requisition_id.pr_line_ids.filtered(lambda x: x.product_id == rec.product_id.product_tmpl_id)
            rec.purchase_qty = sum(line.mapped('qty_received'))
            purchase_line_ids = self.env['purchase.order.line'].search([('pr_line_id', 'in', line.ids)])
            rec.incoming_qty = sum(purchase_line_ids.mapped('qty_received'))